package com.hindua.ailaaicuaai;

import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.hindua.beans.Item;
import com.hindua.tab.scr.StorySrc;
import com.hindua.utils.CustomViewPager;
import com.hindua.utils.NetworkState;
import com.rtst.widget.actionbar.ActionBarActivity;
import com.rtst.widget.tab.SwipeyTabs;
import com.rtst.widget.tab.SwipeyTabsAdapter;
import com.hindua.ailaaicuaai.R;

public class ChapterActivity extends ActionBarActivity {
	private int position;
	private SwipeyTabs mTabs;
	private CustomViewPager mViewPager;
	private String[] TITLES;
	private volatile static ChapterActivity instance;
	private ArrayList<Item> items;
	private int postionBookmark;
	// Change information
	public static final String PEFERENCE_FILE = "pref_hindua_ailaaicuaai";
	private int totalPages = 261;
	private SharedPreferences settings;
	private SharedPreferences.Editor editor;
	
	@SuppressWarnings("unchecked")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		instance = this;
		setContentView(R.layout.activity_custom_swipeytab);
		new NetworkState(ChapterActivity.this).check();
		//position = getIntent().getExtras().getInt("position");
		//this.items = (ArrayList<Item>) getIntent().getExtras().get("items");
		position = 0;
		if (getPositionBookmarked() > 0) {
			position = getPositionBookmarked();
		}
		TITLES = new String[totalPages];
		for (int i = 0; i < totalPages; i ++) {
			TITLES[i] = (i + 1) + "/" + totalPages;
		} 
		mViewPager = (CustomViewPager) findViewById(R.id.viewpager);
		mTabs = (SwipeyTabs) findViewById(R.id.swipeytabs);
		SwipeyTabsPagerAdapter adapter = new SwipeyTabsPagerAdapter(this,
				getSupportFragmentManager());
		mViewPager.setAdapter(adapter);
		mTabs.setAdapter(adapter);
		mViewPager.setOnPageChangeListener(mTabs);
		mViewPager.setPagingEnabled(false);
		mViewPager.setCurrentItem(position);
		this.setPostionBookmark(position);
		Toast.makeText(this, "Vui lòng click vào quảng cáo để ủng hộ tác giả bạn nhé ! ^_^", Toast.LENGTH_LONG).show();
	}
	
	 @Override
		public boolean onCreateOptionsMenu(Menu menu) {
			MenuInflater menuInflater = getMenuInflater();
			menuInflater.inflate(R.menu.chapter, menu);

			// Calling super after populating the menu is necessary here to ensure
			// that the
			// action bar helpers have a chance to handle this event.
			return super.onCreateOptionsMenu(menu);
		}

		@Override
		public boolean onOptionsItemSelected(MenuItem item) {
			switch (item.getItemId()) {
			case android.R.id.home:
				//Toast.makeText(this, "Tapped home", Toast.LENGTH_SHORT).show();
				break;
			case R.id.menu_market:
				Intent intent = new Intent(Intent.ACTION_VIEW);
				intent.setData(Uri.parse("market://search?q=pub%3AViet+Android+J.S.C&c=apps"));
				startActivity(intent);
				break;
			case R.id.menu_bookmark:
				AlertDialog.Builder builder = new AlertDialog.Builder(getInstance());
		        builder.setCancelable(true);
		        builder.setTitle("Ghi nhớ");
		        builder.setMessage("Ứng dụng sẽ nhớ vị trí bạn đang đọc để phục vụ bạn đọc lần sau !");
		        builder.setInverseBackgroundForced(true);
		        builder.setPositiveButton("Có", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                    	ChapterActivity.getInstance().savePositionBookmark(getPostionBookmark());
                        dialog.dismiss();
                    }
                });
		        builder.setNegativeButton("Không", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
					}
				});
		        AlertDialog alert = builder.create();
		        alert.show();
				break;
			}
			return super.onOptionsItemSelected(item);
		}
	
	private class SwipeyTabsPagerAdapter extends FragmentPagerAdapter implements
		SwipeyTabsAdapter {
		
		private final Context mContext;
		public SwipeyTabsPagerAdapter(Context context, FragmentManager fm) {
			super(fm);
			this.mContext = context;
		}
		
		@Override
		public Fragment getItem(int position) {
			try {
				int chapter = position + 1;
				return new StorySrc(position, chapter, getInstance());
			} catch (Exception e) {
				return null;
			}
		}
		
		@Override
		public int getCount() {
			return TITLES.length;
		}
		
		public ViewGroup getTab(final int position, SwipeyTabs root) {
			ViewGroup layout = (ViewGroup) LayoutInflater.from(mContext)
					.inflate(R.layout.swipey_tab_indicator, root, false);
		
			TextView view = (TextView) layout.findViewById(R.id.swipey_tab);
			view.setText(TITLES[position]);
			view.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
					//dau's
					//mViewPager.setCurrentItem(position);
				}
			});
			return layout;
		}
	}
	
	public void nextChapter(int pos) {
		if (pos < this.TITLES.length) {
			setPostionBookmark(pos);
			this.mViewPager.setCurrentItem(pos);
		}
	}
	
	public void prevChapter(int pos) {
		if (pos > 0) {
			setPostionBookmark(pos);
			this.mViewPager.setCurrentItem(pos);
		}
	}

	public static ChapterActivity getInstance() {
		if (instance == null) {
			synchronized (MainActivity.class) {
				if (instance == null) {
					instance = new ChapterActivity();
				}
			}
		}
		return instance;
	}

	public ArrayList<Item> getItems() {
		return items;
	}

	public int getPostionBookmark() {
		return postionBookmark;
	}

	public void setPostionBookmark(int postionBookmark) {
		this.postionBookmark = postionBookmark;
	}
	
	public void savePositionBookmark(int pos) {
		this.settings = getSharedPreferences(PEFERENCE_FILE, 0);
		this.editor = this.settings.edit();
		if (pos >= 0) {
			editor.putInt("positionBookmark", pos);
			editor.commit();
		}
	}
	
	public int getPositionBookmarked() {
		this.settings = getSharedPreferences(PEFERENCE_FILE, 0);
		int pos = this.settings.getInt("positionBookmark", -1);
		return pos;
	}
	
	@Override
	public void onBackPressed() {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage("Bạn muốn đóng ứng dụng ?")
		.setCancelable(true)
		.setPositiveButton("Có", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				finish();
				System.runFinalizersOnExit(true);
				System.exit(0);
			}
		})
		.setNegativeButton("Không", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.cancel();
				onResume();
			}
		});
		AlertDialog alertDialog = builder.create();
		alertDialog.setCancelable(false);
		alertDialog.show();
	}
}
